var Koa = require('koa' );
const request = require("request-promise")
var Router = require('koa-router' );
var app = new Koa();
var router = new Router();
var cloud = require('./cloudApi/index')
const cors = require("@koa/cors")
const koaBody = require('koa-body');
app.use(cors())
const static = require('koa-static');
const path = require('path')
app.use(static(path.join(__dirname, './dist')))
app.use(koaBody({ multipart: true }))
var sha1 = require("sha1");
const wxMessageSend = require('./adminApi/wxMessageSend');

// 云存储方法
var cloudStorage = require('./cloudApi/cloudStorage')

// 登陆
router.post('/vue-admin-template/user/login', (ctx, next)=> {

  ctx.body = {
    code: 200,
    data: {
      token: 'admin-token'
    }
  }
})

// 用户信息
router.get('/vue-admin-template/user/info', (ctx, next)=> {
  ctx.body = {
    code:200,
    data: {
      roles: ['admin'],
      introduction: 'I am a super administrator',
      avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      name: 'Super Admin'
    },
  }
})


// 查询管家列表
router.get( '/housekeep-list', async (ctx, next) => {
  let query = ctx.query;
  console.log()
  let data = await cloud.database(`db.collection('user_list').aggregate()
  .match({
    userType: 2,
    nickName: {
      $regex:'.*${query.name}',
      $options: 'i'
    }
  })
  .lookup({
    from: 'camp_group',
    localField: 'houseKeepOpenid',
    foreignField: 'openid',
    as: 'camp_info',
  })
  .replaceRoot({
    newRoot: $.mergeObjects([$.arrayElemAt(['$camp_info', 0]), '$$ROOT'])
  })
  .project({
    camp_info: 0,
    houseKepp:0,
    houseKeepOpenid: 0,
    houseKeppAvatarUrl: 0,
    houseKeppPhone: 0,
  })
  .end()`, 'aggregate').then((res)=> {
    return res;
  });
  ctx.body = {
    code: 200,
    data,
  }
});

// 查询广告分组
router.get( '/ad-group', async (ctx, next) => {
    let data = await cloud.database(`db.collection('ad_group').limit(100).skip(0).get()`, 'get').then((res)=> {
      return res;
    });
    ctx.body = {
      code: 200,
      data,
    }
});

// 上传文件
router.post('/upload-file', async (ctx, next)=> {
  let file_id = await cloudStorage.upload(ctx).then((res)=> {
    return res;
  })
  let file_list = [{
    fileid: file_id,
    max_age: 7200
  }]

  let fileDownLink = await cloudStorage.download(ctx, file_list).then((res)=> {
    return res;
  })

  ctx.body = {
    code : 200,
    data: fileDownLink,
  }
})


// 新增广告分类
router.get( '/ad-group/add', async (ctx, next) => {
    let query = ctx.query;

    let exist = await cloud.database(`db.collection('ad_group').where({typeName: '${query.typeName}'}).get()`, 'get').then((res)=> {
      return res;
    })
    if (exist.length > 0) {
      ctx.body = {
        code: 500,
        data: {message:'分类名称不能重复'},
      }
    } else {
      let result = await cloud.database(`db.collection('ad_group').add({
        data: {
          typeName: '${query.typeName}',
          status: '${query.status}',
          createTime: '${query.createTime}'
        },
      })`, 'add').then((res)=> {
        return res;
      }); 
      ctx.body = {
        code: 200,
        data: {message: '添加成功'},
      }
    }
});

// 添加广告
router.get('/ad-swiper/add', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('ad_list').add({
    data: {
      group: '${query.group}',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      img: '${query.img}',
      fileid: '${query.fileid}',
      link: '${query.link || ''}',
      sort: '${query.sort || ''}',
      createTime: '${query.createTime}'
    },
  })`, 'add').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 删除广告
router.get('/ad-swiper/remove', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('ad_list').doc('${query.id}').remove()`, 'delete').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 更新广告
router.get('/ad-swiper/update', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('ad_list').doc('${query._id}').update({
    data: {
      group: '${query.group}',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      img: '${query.img}',
      fileid: '${query.fileid}',
      link: '${query.link || ''}',
      sort: '${query.sort || ''}',
      createTime: '${query.createTime}'
    },
  })`, 'update').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 查询广告列表
router.get('/ad-swiper', async (ctx, next)=> {
  let query = ctx.query;
  let skip = (query.pageNum - 1) * 10;
  let result = await cloud.database(`db.collection('ad_list').orderBy('sort','desc').limit(10).skip(${skip}).get()`, 'get').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})



// 新增营地分组
router.get('/camp-group/add', async (ctx, next)=> {
  let query = ctx.query;
  let exist = await cloud.database(`db.collection('camp_group').where({groupCode: '${query.groupCode}'}).get()`, 'get').then((res)=> {
    return res;
  })
  if (exist.length > 0) {
    ctx.body = {
      code: 500,
      data: {message:'分类编码不能重复'},
    }
    return;
  }


  let result = await cloud.database(`db.collection('camp_group').add({
    data: {
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      status: '${query.status}',
      houseKeepOpenid: '${query.houseKeepOpenid}',
      remarks: '${query.remarks || ''}',
      sort: '${query.sort || ''}',
      houseKepp: '${query.houseKepp}',
      houseKeppAvatarUrl: '${query.houseKeppAvatarUrl}',
      createTime: '${query.createTime}',
      houseKeppPhone: '${query.houseKeppPhone}',
    },
  })`, 'add').then((res)=> {
    return res;
  }); 

  ctx.body = {
    code: 200,
    data: result,
  }
})

// 更新营地分组
router.get('/camp-group/update', async (ctx, next)=> {
  let query = ctx.query;

  let result = await cloud.database(`db.collection('camp_group').doc('${query._id}').update({
    data: {
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      status: '${query.status}',
      houseKeepOpenid: '${query.houseKeepOpenid}',
      houseKeppPhone: '${query.houseKeppPhone}',
      remarks: '${query.remarks || ''}',
      houseKepp: '${query.houseKepp}',
      sort: '${query.sort || ''}',
      houseKeppAvatarUrl: '${query.houseKeppAvatarUrl}',
      createTime: '${query.createTime}',
    },
  })`, 'update').then((res)=> {
    return res;
  }); 

  ctx.body = {
    code: 200,
    data: result,
  }
})

// 删除营地分组
router.get('/camp-group/remove', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('camp_group').doc('${query.id}').remove()`, 'delete').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})


// 查询营地分类列表
router.get('/camp-group', async (ctx, next)=> {
  let query = ctx.query;
  // let skip = (query.pageNum - 1) * 10;
  let result = await cloud.database(`db.collection('camp_group').orderBy('sort','desc').limit(100).skip(0).get()`, 'get').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 新增营位
router.get('/camp-list/add', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('camp_list').add({
    data: {
      imgJson: '${query.imgJson}',
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      groupCode_txt: '${query.groupCode_txt}',
      people: '${query.people || ''}',
      campArea: '${query.campArea || ''}',
      sort: '${query.sort || ''}',
      bookingDate: '[]',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      recommend: '${query.recommend || ''}',
      img: '${query.img}',
      desc: '${query.desc}',
      fileid: '${query.fileid}',
      createTime: '${query.createTime}',
    },
  })`, 'add').then((res)=> {
    return res;
  }); 

  ctx.body = {
    code: 200,
    data: result,
  }
})

// 查询营位列表
router.get('/camp-list', async (ctx, next)=> {
  let query = ctx.query;
  let skip = (query.pageNum - 1) * 10;
  let result = await cloud.database(`db.collection('camp_list').orderBy('createTime', 'desc').orderBy('sort', 'desc').limit(10).skip(${skip}).get()`, 'get').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})


// 更新营位列表
router.get('/camp-list/update', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('camp_list').doc('${query._id}').update({
    data: {
      title: '${query.title}',
      imgJson: '${query.imgJson}',
      groupCode: '${query.groupCode}',
      groupCode_txt: '${query.groupCode_txt}',
      people: '${query.people || ''}',
      campArea: '${query.campArea || ''}',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      sort: '${query.sort || ''}',
      recommend: '${query.recommend || ''}',
      img: '${query.img}',
      desc: '${query.desc}',
      fileid: '${query.fileid}',
      createTime: '${query.createTime}',
    },
  })`, 'update').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 删除营位
router.get('/camp-list/remove', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('camp_list').doc('${query.id}').remove()`, 'delete').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})




// 新增商品
router.get('/goods-list/add', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('goods_list').add({
    data: {
      imgJson: '${query.imgJson}',
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      groupCode_txt: '${query.groupCode_txt}',
      price: '${query.price || ''}',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      recommend: '${query.recommend || ''}',
      img: '${query.img}',
      inventory: '${query.inventory || ''}',
      desc: '${query.desc || ''}',
      fileid: '${query.fileid}',
      createTime: '${query.createTime}',
    },
  })`, 'add').then((res)=> {
    return res;
  }); 

  ctx.body = {
    code: 200,
    data: result,
  }
})

// 查询商品列表
router.get('/goods-list', async (ctx, next)=> {
  let query = ctx.query;
  let skip = (query.pageNum - 1) * 10;
  let result = await cloud.database(`db.collection('goods_list').orderBy('createTime', 'desc').where({
    title: {
      $regex:'.*${query.goodsName}',
      $options: 'i'
    },
  }).limit(10).skip(${skip}).get()`, 'get').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})


// 更新商品列表
router.get('/goods-list/update', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('goods_list').doc('${query._id}').update({
    data: {
      imgJson: '${query.imgJson}',
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      groupCode_txt: '${query.groupCode_txt}',
      price: '${query.price || ''}',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      recommend: '${query.recommend || ''}',
      inventory: '${query.inventory || ''}',
      img: '${query.img}',
      desc: '${query.desc || ''}',
      fileid: '${query.fileid}',
      createTime: '${query.createTime}',
    },
  })`, 'update').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 删除商品
router.get('/goods-list/remove', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('goods_list').doc('${query.id}').remove()`, 'delete').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})



// 新增商品分组
router.get('/goods-group/add', async (ctx, next)=> {
  let query = ctx.query;

  let exist = await cloud.database(`db.collection('goods_group').where({groupCode: '${query.groupCode}'}).get()`, 'get').then((res)=> {
    return res;
  })
  if (exist.length > 0) {
    ctx.body = {
      code: 500,
      data: {message:'分类编码不能重复'},
    }
    return;
  }

  let result = await cloud.database(`db.collection('goods_group').add({
    data: {
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      status: '${query.status}',
      remarks: '${query.remarks || ''}',
      sort: '${query.sort || ''}',
      createTime: '${query.createTime}',
    },
  })`, 'add').then((res)=> {
    return res;
  }); 

  ctx.body = {
    code: 200,
    data: result,
  }
})

// 查询商品分组
router.get('/goods-group', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('goods_group').orderBy('sort', 'desc').limit(100).skip(0).get()`, 'get').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})


// 更新商品分组
router.get('/goods-group/update', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('goods_group').doc('${query._id}').update({
    data: {
      title: '${query.title}',
      groupCode: '${query.groupCode}',
      status: '${query.status}',
      sort: '${query.sort || ''}',
      remarks: '${query.remarks || ''}',
      createTime: '${query.createTime}',
    },
  })`, 'update').then((res)=> {
    return res;
  });

  ctx.body = {
    code: 200,
    data: result,
  }
})

// 删除商品分组
router.get('/goods-group/remove', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database(`db.collection('goods_group').doc('${query.id}').remove()`, 'delete').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})


// 查询订单列表
router.get('/order-list', async (ctx, next)=> {
  let query = ctx.query;
  let skip = ((query.pageNum || 1) - 1) * 10;
  let count = await cloud.database(`
  db.collection('order_list').aggregate().sort({
    creatTime: -1,
  })
  .match({
    orderCode: {
      $regex:'.*${query.orderCode || ''}',
      $options: 'i'
    },
  })
  .lookup({
    from: 'user_list',
    localField: 'openid',
    foreignField: 'openid',
    as: 'userInfo'
  })
  .replaceRoot({
    newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
  })
  .match({
    phone: {
      $regex:'.*${query.phone || ''}',
      $options: 'i'
    },
  })
  .lookup({
    from: 'camp_list',
    localField: 'campId',
    foreignField: '_id',
    as: 'campInfo'
  })
  .project({
    campId: 0,
    userInfo: 0,
  })
  .skip(${skip})
  .limit(10)
  .count('Total')
  .end()
  `, 'aggregate').then((res)=> {
    return res;
  }); 

  let result = await cloud.database(`
  db.collection('order_list').aggregate().sort({
    creatTime: -1,
  })
  .match({
    orderCode: {
      $regex:'.*${query.orderCode || ''}',
      $options: 'i'
    },
  })
  .lookup({
    from: 'user_list',
    localField: 'openid',
    foreignField: 'openid',
    as: 'userInfo'
  })
  .replaceRoot({
    newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
  })
  .match({
    phone: {
      $regex:'.*${query.phone || ''}',
      $options: 'i'
    },
  })
  .lookup({
    from: 'camp_list',
    localField: 'campId',
    foreignField: '_id',
    as: 'campInfo'
  })
  .project({
    campId: 0,
    userInfo: 0,
  })
  .skip(${skip})
  .limit(10)
  
  .end()
  `, 'aggregate').then((res)=> {
    return res;
  }); 


  let obj = {};
  obj.list = result;
  obj.Offset = skip;
  obj.Total = count.length > 0 ? Number(count[0].Total.$numberInt) : 0;
  ctx.body = {
    code: 200,
    data: obj,
  };
})


// 取消订单
router.get('/order-list/cancel', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database({
    name: 'cancel_order',
    POSTBODY: {
      id: query.id,
    },
  }, 'cloundFunction').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 派送
router.get('/order-list/dispatch', async (ctx, next)=> {
  let query = ctx.query;
  let result = await cloud.database({
    name: 'dispatch',
    POSTBODY: {
      id: query.id,
      openid: query.openid,
    },
  }, 'cloundFunction').then((res)=> {
    return res;
  }); 
  ctx.body = {
    code: 200,
    data: result,
  }
})

// 取消预约列表
router.get('/reservation-cancel', async (ctx, next)=> {
  let query = ctx.query;

  let userbookingDate = await cloud.database(`db.collection('reservation_list').doc('${query.id}').get()`, 'get').then((res)=> {
    return res.list[0].bookingDate;
  }); 

  // 修改预约状态
  let result = await cloud.database(`db.collection('reservation_list').doc('${query.id}').update({
    data: {
      status: '2',
    },
  })`, 'update').then((res)=> {
    return res;
  }); 

  // 释放营位预约
  let result2 = await cloud.database(`db.collection('camp_list').doc('${query.campId}').get()`, 'get').then((res)=> {
    return res.list[0];
  }); 
  let cmapDate = JSON.parse(result2.bookingDate);
  for (var i = 0; i < userbookingDate.length; i++) {
    
    let index = cmapDate.findIndex((item)=> item == userbookingDate[i] );
    if (index > -1) {
      cmapDate.splice(index, 1);
    }
  }

  let result4 = await cloud.database(`db.collection('camp_list').doc('${query.campId}').update({
    data: {
      bookingDate: '${JSON.stringify(cmapDate)}',
    },
  })`, 'update').then((res)=> {
    return res;
  }); 





  ctx.body = {
    code: 200,
    data: result,
  }
})


// 查询预约列表
router.get('/reservation-list', async (ctx, next)=> {
  let query = ctx.query;
  let skip = ((query.pageNum || 1) - 1) * 10;
  let count = await cloud.database(`
  db.collection('reservation_list').aggregate()
  .sort({
    creatTime: -1,
  })
  .lookup({
    from: 'user_list',
    localField: 'openid',
    foreignField: 'openid',
    as: 'userInfo'
  })
  .replaceRoot({
    newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
  })
  .project({
    userInfo: 0,
  })
  .match({
    bookingDate: {
      $regex:'.*${query.searchDay || ''}',
      $options: 'i'
    },
    phone: {
      $regex:'.*${query.phone || ''}',
      $options: 'i'
    },
  })
  .skip(${skip})
  .limit(10)
  .count('Total')
  .end()
  `, 'aggregate').then((res)=> {
    return res;
  }); 

  let result = await cloud.database(`
  db.collection('reservation_list').aggregate()
  .sort({
    creatTime: -1,
  })
  .lookup({
    from: 'user_list',
    localField: 'openid',
    foreignField: 'openid',
    as: 'userInfo'
  })
  .replaceRoot({
    newRoot: $.mergeObjects([$.arrayElemAt(['$userInfo', 0]), '$$ROOT'])
  })
  .project({
    userInfo: 0,
  })
  .match({
    bookingDate: {
      $regex:'.*${query.searchDay || ''}',
      $options: 'i'
    },
    phone: {
      $regex:'.*${query.phone || ''}',
      $options: 'i'
    },
  })
  .skip(${skip})
  .limit(10)
  .end()
  `, 'aggregate').then((res)=> {
    return res;
  }); 

  let obj = {};
  obj.list = result;
  obj.Offset = skip;
  obj.Total = count.length > 0 ? Number(count[0].Total.$numberInt) : 0;
  ctx.body = {
    code: 200,
    data: obj,
  }
})







// 查询仪表盘数据
router.get('/dashboard-data', async (ctx)=> {



  let result = await cloud.database({
      name: 'dashboard',
    }, 'cloundFunction').then((res)=> {
      return res;
  }); 
  ctx.body = {
    code: 200,
    data:{
      result,
    },
  };
})

  // 微信公众号配置
  router.get("/api/weixin", (req, res) => {
    var token = 'muyeyingshi';
    var signature = req.query.signature;
    var nonce = req.query.nonce;
    var timestamp = req.query.timestamp;
    var echostr = req.query.echostr;
    var str = [token, timestamp, nonce].sort().join("");
    var sha = sha1(str);
    if (signature === sha) {
      console.log(1);
      return req.body = echostr;
    } else {
      console.log(2);
      console.log("error");
    }
  });


  // 发送模板消息
  router.get('/send/message/tmp', (ctx)=> {
    wxMessageSend({
      openid: 'opk4c61XXtsV4CxW8a9d-LRAtW4k',
      templateId: 'eUUxAmOS85agYBVvwa1-OAqPNoH2cRfWs9OMk31zIzE',
      url: 'https://camp.muyys.cn/#/mobile/goodList?orderCode=' + ctx.query.orderCode,
      data: {
        character_string1: {
            value: new Date().getTime(),
            color: "#00FF00"
        },
        amount5: {
            value: "380",
            color: "#173177"
        },
        thing8: {
            value: "用户下单了，请尽快配送",
            color: "#173177"
        },
      },
    });
    ctx.body = '发送成功'
  })




//使用路由中间件
app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen( 55555 )